package org.bite.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.bite.captcha.Constants;
import org.bite.captcha.model.CaptchaProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final static long session_valid_timeout = 60*1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());

        //图型验证码写出,可以写出到文件,也可以写出到流
        try {
            lineCaptcha.write(response.getOutputStream());  //返回到浏览器

            //得到函数生成的验证码
            String code = lineCaptcha.getCode();  //得到函数生成的验证码

            //存储到session
            //必须考虑到多线程访问,因为有多个用户访问,把每个用户生成的验证码存放到对应用户的session里面
            session.setAttribute(captchaProperties.getSession().getKey(), code);
            //获取一个时间戳存入session,来设置验证码的有效期(这是得到设置code的时间戳)
            session.setAttribute(captchaProperties.getSession().getDate(),new Date());

            response.getOutputStream().close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String inputCode, HttpSession session) {
        //验证码生成的内容和用户输入的内容进行比较
        if (!StringUtils.hasLength(inputCode)) {  //如果为空
            return false;
        }
        //从session获取信息
        String saveCode = (String) session.getAttribute(captchaProperties.getSession().getKey());  //前端页面生成的验证码
        Date saveData = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if(inputCode.equalsIgnoreCase(saveCode)) {  //忽略大小写进行判断
            //判断验证码是否过期
            if (saveData != null && System.currentTimeMillis()-saveData.getTime() < session_valid_timeout){
                return true;
            }

        }
        return false;
    }
}
